(() => {
  // 创建 Vue 实例并挂载到 id 为 main 的元素上
  new Vue({
    el: "#main",
    mixins: [mixin],
    data: {
      subtxt: 50,
      // 定义数据
      AIData: {
        "warningId": "",//"string //当前预警ID",
        "confirmColor": "",//"string //预警颜色: 红色-收到预警未确认预警; 黄色-收到预警已确认但未反馈 未反馈是指当前预警ID在确认预警的那个时间以及之后没有诊断记录、没有治疗方案",
        diagnosis: "",//string //诊断",
        showName: "",//string //模型名称",
        "modelName": "" ,//string //模型名称",
        "isVisible": "" ,//"string //模型名称对用户是否可见, 1可见  0 不可见",
        "predictTimeWindow": "" ,//"string //预测时间窗口（模型那边的）",
        "model0hInterpretability": "" ,//"string //0h模型可解释性,即解释主要采用哪个特征进行的预测",
        "model3hInterpretability": "" ,//"string //3h模型可解释性,即解释主要采用哪个特征进行的预测",
        "patientAiWarningInfoId": "",// //病患预警信息主键ID",
        "doctorInfoId": "",// //医生表主键ID",
        "patientInfoId": "",// //病患表主键ID",
        "modelId": "",// //模型ID",
        "isConfirmWarning": "",// //医生是否确认收到预警  1-是; 0-否",
        "confirmWarningTime": "",// //医生确认收到预警的时间",
        "currentProbabilityOfSepsis": "",// //模型预测当前发生脓毒症概率  百分值",
        "next3hProbabilityOfSepsis": "",////模型预测接下来3小时发生脓毒症概率  百分值",
        "modelInterpretability": "",// //模型可解释性,即解释主要采用哪个特征进行的预测",
        "modelExecutionFrequency": "",// //模型执行频率",
        "isPushPredictResult": "",// //模型预测结果是否有推送  1-是; 0-否",
        "pushedTime": "",// //模型预测结果推送时间",
        "createdDate": "",//,
        "createdBy": "",//,
        "updatedDate": "",//,
        "updatedBy": "",//
        isContainDiagnosis:"", // 是否包含诊断信息 1包含0 未包含
        isContainTreatment:"" // 是否包含质量治疗方案 1包含0 未包含
      },
      modelHourData:0,
      // Field backup
      // FieldbackupList:[],
      // "id":"int //药物类型信息主键ID",
      //   "medicalType":"string //药物类型名称",
      //   "drugSpecifications":"string //药物类型用量",
      //   "drugUnit":"string //药物类型用量单位",
      //   "diluteSpecifications":"string //药物类型稀释溶液用量",
      //   "diluteUnit":"string //药物类型稀释溶液用量单位",
      //   "dilute":"string //药物类型稀释溶液名称"
      medicalList: [
        // {
        //   medicalType: "药品1",
        //   dilute: "1",
        //   drugUnit: "bottle",
        //   diluteUnit: "1",
        //   drugSpecifications: "1",
        //   diluteSpecifications: "1",
        // },
        // {
        //   medicalType: "药品2",
        //   dilute: "2",
        //   drugUnit: "box",
        //   diluteUnit: "2",
        //   drugSpecifications: "2",
        //   diluteSpecifications: "2",
        // }
      ],// 药物列表
      filteredColumns: [],
      searchText: '',
      showmedicalType: false,
      medicalListHide: false,
      // 治疗方案对象
      treatmentPlan: {
        medicalType: "",
        dilute: "",
        drugUnit: "",
        diluteUnit: "",
        drugSpecifications: "",
        diluteSpecifications: "",
        frequency: "", //频次
      },
      TreatmentPlanList: [], //治疗方案列表
      DiagnosticList: [],
      toDelData:null,
      delType:"",
      option: [
        { text: '盒', value: 'box'  },
        { text: '瓶', value: 'bottle'  },
        { text: 'g', value: 'g'  },
        { text: 'mg', value: 'mg'  },
        { text: 'ml', value: 'ml'  },
        { text: 'mm', value: 'mm'  },
        { text:'iu', value:'iu'  },
        { text:'µg/kg·min', value:'µg/kg·min'  },
      ],
      showfrequency: false,
      // 单次  Q6h  Q8h Q12h   Qd   Tid  Bid  Qid  Qod
      frequencyColumns: [
        "单次",
        "Q6h",
        "Q8h",
        "Q12h",
        "Qd",
        "Tid",
        "Bid",
        "Qid",
        "Qod"
      ]
    },
    created () {
      this.filteredColumns = [...this.medicalList]
      toastr.options = {
        positionClass: 'toast-top-center'
      };
      // 判断是否带有参数 如果有 
      // 初始化页面 需要获取当前医生信息
      let url_ = window.location.href
      let data = this.getUrlParams(url_)
      if(Object.keys(data).length){ 
        // 如果已经
        // 更新一下患者id方便切换页面做 病人信息查询
        sessionStorage.setItem("patientInfoId", data.patientInfoId)
        // 更新医生信息
        let doctorTestData = {
          doctorId: data.doctorId,
          doctorInfoId: data.doctorInfoId,
          doctorName: data.doctorName,
          doctorType: data.doctorType,
          hospitalInfoId: data.hospitalInfoId
        }
        sessionStorage.setItem("doctorTestData",JSON.stringify(doctorTestData))
        this.initData()
        // 页面加载完成后执行的方法
        this.getAllPatientList()
        this.getmedicalList()
      }else{
        this.initData()
        // 页面加载完成后执行的方法
        this.getAllPatientList()
        this.getmedicalList()
      }
      
    },
    methods: {
      // 定义方法
      // 切换患者信息 
      changePatient () {
        $('#staticBackdrop').modal('show');
      },
      changePatientHander (item) {
        // 确认选择患者 更新患者信息 并通过患者id查询当前患者基础信息及病症信息
        this.getPaitentDetail(item.patientInfoId)
        // 
        $('#staticBackdrop').modal('hide');
      },
      // 获取患者详情 
    getPaitentDetail (patientInfoId) {
      const URL = "/patient/detail?patientInfoId=" + patientInfoId;
      fetch(apiUrl + URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          if (data.code === 200) {
            // 更新一下患者id方便切换页面做 病人信息查询
            sessionStorage.setItem("patientInfoId", patientInfoId)
            this.patientInfo.patientDiseaseDetailList = []
            Object.assign(this.patientInfo, data.data)
            this.getDiagnosticList()
            this.getAIData()
            this.getTreatmentPlanList()
          } else {
            console.error(data.msg);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
    aidata(){
      return{
          "warningId": "",//"string //当前预警ID",
          "confirmColor": "",//"string //预警颜色: 红色-收到预警未确认预警; 黄色-收到预警已确认但未反馈 未反馈是指当前预警ID在确认预警的那个时间以及之后没有诊断记录、没有治疗方案",
          diagnosis: "",//string //诊断",
          showName: "",//string //模型名称",
          "modelName": "" ,//string //模型名称",
          "isVisible": "" ,//"string //模型名称对用户是否可见, 1可见  0 不可见",
          "predictTimeWindow": "" ,//"string //预测时间窗口（模型那边的）",
          "model0hInterpretability": "" ,//"string //0h模型可解释性,即解释主要采用哪个特征进行的预测",
          "model3hInterpretability": "" ,//"string //3h模型可解释性,即解释主要采用哪个特征进行的预测",
          "patientAiWarningInfoId": "",// //病患预警信息主键ID",
          "doctorInfoId": "",// //医生表主键ID",
          "patientInfoId": "",// //病患表主键ID",
          "modelId": "",// //模型ID",
          "isConfirmWarning": "",// //医生是否确认收到预警  1-是; 0-否",
          "confirmWarningTime": "",// //医生确认收到预警的时间",
          "currentProbabilityOfSepsis": "",// //模型预测当前发生脓毒症概率  百分值",
          "next3hProbabilityOfSepsis": "",////模型预测接下来3小时发生脓毒症概率  百分值",
          "modelInterpretability": "",// //模型可解释性,即解释主要采用哪个特征进行的预测",
          "modelExecutionFrequency": "",// //模型执行频率",
          "isPushPredictResult": "",// //模型预测结果是否有推送  1-是; 0-否",
          "pushedTime": "",// //模型预测结果推送时间",
          "createdDate": "",//,
          "createdBy": "",//,
          "updatedDate": "",//,
          "updatedBy": "",//
          isContainDiagnosis:"", // 是否包含诊断信息 1包含0 未包含
          isContainTreatment:"" // 是否包含质量治疗方案 1包含0 未包含
      }
    },
      // 获取AI预警信息
      getAIData () {
        const patientInfoId = sessionStorage.getItem("patientInfoId")
        const URL = "/patient/ai/warning/detail?patientInfoId=" + patientInfoId;
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          // body: JSON.stringify({
          //   patientInfoId: patientInfoId,
          // })
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              Object.assign(this.AIData,this.aidata())
              if(data.data) Object.assign(this.AIData,data.data)
              console.log(data, "AI预警信息",this.AIData)
              if(this.AIData && this.AIData.model0hInterpretability){
                this.AIData.model0hInterpretability = JSON.parse(this.AIData.model0hInterpretability)
              } else{
                this.AIData.model0hInterpretability = []
              }
              if(this.AIData && this.AIData.model3hInterpretability){
                this.AIData.model3hInterpretability = JSON.parse(this.AIData.model3hInterpretability)
              }else{
                this.AIData.model3hInterpretability = []
              }
              console.log(this.AIData.model0hInterpretability)
              console.log(this.AIData.model3hInterpretability)
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 确认收到预警
      Confirmwarning () {
        // /patient/ai/warning/upadte/confirm
        // {
        //   "patientAiWarningInfoId":"int //病患预警信息主键ID【必须】",
        //   "isConfirmWarning":"string //医生是否确认收到预警  1-是; 0-否【必须】",
        //   "confirmWarningTime":"date //确认收到预警的时间",
        //   "updatedBy":"string //更新人"
        // }
        if(!this.AIData.warningId){
          toastr.error("病患预警信息主键为空！")
          return
        }
        const URL = "/patient/ai/warning/upadte/confirm" ;
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            patientAiWarningInfoId: this.AIData.patientAiWarningInfoId,
            isConfirmWarning:1
          })
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
             this.getAIData()
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      modelHour(e){
        this.modelHourData = e
      },
      // 提交当前诊断
      subDiagnosticMsg () {

        // 有预警时，在提交诊断反馈或治疗方案时 需要判断是否已经确认预警，未确认不能提交
        //patient/diagnosis/add
        // "doctorInfoId":"int //医生主键【必须】",
        // "patientInfoId":"int //病患主键【必须】",
        // "warningId":"string //预警ID【必须】",
        // "operationValue":"double //病患确诊患脓毒症的程度  百分值【必须】",
        // "createdBy":"string //创建人",
        // "updatedBy":"string //更新人"
        if(this.AIData.confirmColor == "red"){
          toastr.error("请先确认预警信息，再添加诊断方案！")
          return
        }
        const treatmentContent = JSON.stringify(this.treatmentPlan)
        const patientInfoId = sessionStorage.getItem("patientInfoId")
        const data = {
          doctorInfoId: this.patientInfo.doctorInfoId,
          patientInfoId: patientInfoId,
          warningId: this.patientInfo.warningId,
          operationValue: this.subtxt/100
        }
        const URL = "/patient/diagnosis/add";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              console.log(data, "提交信息")
              toastr.success(data.msg ? data.msg : "操作成功！")
              // 更新诊断文书列表
              this.getAIData()
              this.getDiagnosticList()
              this.getTreatmentPlanList()
            } else {
              toastr.error(data.msg ? data.msg : "操作失败！")
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });


      },
      inspectiondel (e,type) {
        // 删除检查项 后刷新检查项列表
        this.toDelData = e
        this.delType = type
        $('#confirmModaldel').modal('show');

      },
      todel(){
        if(this.delType == 1){
          // 删除诊断反馈 
          this.DiagnosticDele()
        }else if(this.delType == 2){
          // 删除治疗方案
          this.TreatmentPlanDele()
        }
      },
      // 删除诊断方案
      DiagnosticDele () {
        const URL = "/patient/diagnosis/delete";
        fetch(apiUrl + URL, {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify([this.toDelData.patientDiagnosisInfoId])
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              $('#confirmModaldel').modal('hide');
              toastr.success(data.msg ? data.msg : "删除成功！")
              this.getDiagnosticList()
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 获取诊断文书列表
      getDiagnosticList () {
        const data = {
          patientInfoId: sessionStorage.getItem("patientInfoId"),
          // warningId: "1"
        }
        const URL = "/patient/diagnosis/list?patientInfoId=" + data.patientInfoId;
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          // body: JSON.stringify(data)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              console.log(data, "诊断文书列表")
              this.DiagnosticList = data?.data ?? []
            } else {
              toastr.error(data.msg ? data.msg : "操作失败！")
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      /**
       * 提交当前治疗方案
       * "doctorInfoId":"int //医生主键【必须】",
        "patientInfoId":"int //病患主键【必须】",
        "warningId":"string //预警ID【必须】",
        "treatmentContent":"string //治疗方案内容【必须】",
        "createdBy":"string //创建人",
        "updatedBy":"string //更新人"
       * 
       */
      subTreatmentPlan () {
        if(this.AIData.confirmColor == "red"){
          toastr.error("请先确认预警信息，再添加治疗方案！")
          return
        }
        if(!this.treatmentPlan.medicalType){
          toastr.error("请选择药品！")
          return
        }
        const treatmentContent = JSON.stringify(this.treatmentPlan)
        const patientInfoId = sessionStorage.getItem("patientInfoId")
        const data = {
          doctorInfoId: this.patientInfo.doctorInfoId,
          patientInfoId: patientInfoId,
          warningId: this.patientInfo.warningId,
          treatmentContent: treatmentContent
        }
        const URL = "/patient/treatment/add";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              console.log(data, "提交信息")
              toastr.success(data.msg ? data.msg : "操作成功！")
              // 更新治疗方案列表
              // 重置治疗方案
              this.treatmentPlan= {
                medicalType: "",
                dilute: "",
                drugUnit: "",
                diluteUnit: "",
                drugSpecifications: "",
                diluteSpecifications: "",
              }
              this.getAIData()
              this.getTreatmentPlanList()
            } else {
              toastr.error(data.msg ? data.msg : "操作失败！")
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 添加频次
      onConfirmfrequency (val) {
        this.showfrequency = false;
        this.treatmentPlan.frequency = val;
      },
      medicalFilter(e){
        // 药物列表过滤功能
        if (!this.searchText) {
          this.filteredColumns = [...this.medicalList];
          return;
        }
        this.filteredColumns = this.medicalList.filter(item =>
          item.medicalType.includes(this.searchText)
        );
      },
      diluteHander(){
        // console.log(this.treatmentPlan.dilute)
        if(this.treatmentPlan.dilute&&this.treatmentPlan.dilute == '无'){
          this.treatmentPlan.diluteSpecifications = "无"
        }else{
          this.treatmentPlan.diluteSpecifications = "100"
        }
      },
      onConfirm (val) {
        this.medicalListHander(val)
        this.showmedicalType = false
        this.searchText = ""
        this.medicalFilter()
      },
      medicalListHander (item) {
        // console.log(item, "当前选中药物")
        this.treatmentPlan.medicalType = item.medicalType
        this.treatmentPlan.dilute = item.dilute
        this.treatmentPlan.drugUnit = item.drugUnit
        this.treatmentPlan.diluteUnit = item.diluteUnit
        this.treatmentPlan.drugSpecifications = item.drugSpecifications
        this.treatmentPlan.diluteSpecifications = item.diluteSpecifications
      },
      // 获取药物列表 
      getmedicalList () {
        const URL = "/dict/medical/name/list";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          // body: JSON.stringify({
          //   patientInfoId: patientInfoId,
          // })
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              console.log(data.data, "药物信息")
              this.medicalList = data?.data ?? []
              this.filteredColumns = [...this.medicalList]
              // this.FieldbackupList = JSON.parse(JSON.stringify(this.medicalList))
            } else {
              toastr.error(data.msg ? data.msg : "操作失败！")
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 获取治疗方案列表
      getTreatmentPlanList () {
        // 
        // patientInfoId
        // warningId
        const data = {
          patientInfoId: sessionStorage.getItem("patientInfoId"),
          // warningId: "1"
        }
        const URL = "/patient/treatment/list?patientInfoId=" + data.patientInfoId;
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          // body: JSON.stringify(data)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              console.log(data, "获取治疗方案列表")
              this.TreatmentPlanList = data?.data ?? []
              // 每次查询治疗方案第一个做回显处理
              if(this.TreatmentPlanList.length){
                let data = this.treatmentContentTiemSet(this.TreatmentPlanList[0].treatmentContent)
                this.treatmentPlan = data
              }
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });

      },
      // 质量方案列表渲染 对象整合 方法 
      // "id":"int //药物类型信息主键ID",
      //             "medicalType":"string //药物类型名称",
      //             "drugSpecifications":"string //药物类型用量",
      //             "drugUnit":"string //药物类型用量单位",
      //             "diluteSpecifications":"string //药物类型稀释溶液用量",
      //             "diluteUnit":"string //药物类型稀释溶液用量单位",
      //             "dilute":"string //药物类型稀释溶液名称"
      treatmentContentTiemSet (e) {
        if (e) {
          const { medicalType = "", drugSpecifications = "", drugUnit = "", diluteSpecifications = "", diluteUnit = "", dilute = "", frequency = "" } = JSON.parse(e);
          return {
            medicalType: medicalType, drugSpecifications: drugSpecifications, drugUnit: drugUnit, diluteSpecifications: diluteSpecifications, diluteUnit: diluteUnit, dilute: dilute, frequency:frequency
          }
        } {
          return {
            medicalType: "", drugSpecifications: "", drugUnit: "", diluteSpecifications: "", diluteUnit: "", dilute: "",frequency:""
          }
        }

      },
      // 删除治疗方案 /patient/treatment/delete
      TreatmentPlanDele () {
        const URL = "/patient/treatment/delete";
        fetch(apiUrl + URL, {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify([this.toDelData.patientTreatmentInfoId])
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              $('#confirmModaldel').modal('hide');
              toastr.success(data.msg ? data.msg : "删除成功！")
              this.getTreatmentPlanList()
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 更新患者确诊信息
      updatePatientdiagnosisMsg () {
        // /patient/upadte/diagnosed  
        // {
        //   "patientInfoId":"int //病患主键【必须】",
        //   "isDiagnosedWithSepsis":"string //是否确诊为脓毒症 1-是;0-否【必须】",
        //   "diagnosedTime":"date //确诊为脓毒症的时间",
        //   "updatedBy":"string //更新人"
        // }
        const data = {
          patientInfoId: sessionStorage.getItem("patientInfoId"),
          isDiagnosedWithSepsis: "1",
          diagnosedTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        const URL = "/patient/upadte/diagnosed";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              toastr.success(data.msg ? data.msg : "操作成功！")
              // 更新患者信息 
              this.initData()
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });

      },
      // 更新患者出院信息
      updatePatientdischargeMsg () {
        // /patient/upadte/admission
        // {
        //   "patientInfoId":"int //病患主键【必须】",
        //   "isPatientDischarged":"string //病患是否出院 1-是;0-否【必须】",
        //   "dischargedTime":"date //病患出院时间",
        //   "updatedBy":"string //更新人"
        // }
        const data = {
          patientInfoId: sessionStorage.getItem("patientInfoId"),
          isPatientDischarged: "1",
          dischargedTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        const URL = "/patient/upadte/admission";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              toastr.success(data.msg ? data.msg : "操作成功！")
              // 更新患者信息 
              this.initData()
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
	  // 已死亡停止监测
      updatePatientdieMsg () {
        // /patient/upadte/admission
        // {
        //   "patientInfoId":"int //病患主键【必须】",
        //   "isPatientDischarged":"string //病患是否出院 1-是;0-否【必须】",
        //   "dischargedTime":"date //病患出院时间",
        //   "updatedBy":"string //更新人"
        // }
        const data = {
          patientInfoId: sessionStorage.getItem("patientInfoId"),
          isPatientDie: "1",
          dieTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        const URL = "/patient/upadte/isDie";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data)
        })
            .then((response) => {
              return response.json();
            })
            .then((data) => {
              if (data.code === 200) {
                toastr.success(data.msg ? data.msg : "操作成功！")
                // 更新患者信息
                this.initData()
              } else {
                console.error(data.msg);
              }
            })
            .catch((error) => {
              console.error(error);
            });
      },
    },
  });
})();
